import { readFile } from 'fs/promises';
import { globbyStream } from 'globby';
import { parseArgs } from 'util';
import { build, createServer, InlineConfig } from 'vite';
import { _userscript } from './_userscript.js';

const pkg = JSON.parse(await readFile('package.json', 'utf8'));

const args = parseArgs({
	options: {
		production: {
			type: 'boolean',
			default: false
		}
	}
});

const server = await createServer({
	plugins: [
		{
			name: 'rewrite',
			configureServer(server) {
				server.middlewares.use(async (req, res, next) => {
					req.url = '/out' + req.url;
					next();
				});
			}
		}
	],
	optimizeDeps: {
		disabled: true
	}
});

if (!args.values.production) {
	await server.listen();
	await server.printUrls();
}

const entries: string[] = [];
for await (const path of await globbyStream('src/**/main.ts')) {
	const code = await readFile(path, { encoding: 'utf8' });
	if (!code.startsWith('// ==UserScript==')) continue;
	entries.push(path.toString());
}

const configs = entries.map<InlineConfig>(entry => ({
	mode: args.values.production ? 'production' : 'development',
	plugins: [
		_userscript({
			entry: entry,
			format: 'umd',
			port: server.config.server.port,
			cdn: args.values.production ? pkg.homepage : '',
		})
	],
	build: {
		watch: args.values.production ? undefined : {},
		outDir: args.values.production ? 'dist/' : 'out/'
	}
}));

await Promise.all(configs.map(build));
if (args.values.production) await server.close();
